import { Assets } from 'pixi.js';

class ResourceManager {
    static resourceMap = new Map();
    static loadingPromises = new Map();

    static async loadAll() {
        const resources = {
            mario_left: './mario/left.png',
            mario_right: './mario/right.png',
            mario_jump_left: './mario/jump_left.png',
            mario_jump_right: './mario/jump_right.png',
            cloud: './cloud.png',
            stone: './stone.png',
            sand: './sand.png',
            tree: './tree1.png',
            mountain: './mountain.png'
        };

        const loadPromises = Object.entries(resources).map(async ([name, url]) => {
            const texture = await Assets.load(url);
            this.resourceMap.set(name, texture);
            return { name, texture };
        });

        await Promise.all(loadPromises);
        return this.resourceMap;
    }

    static async load(name, url) {
        if (this.loadingPromises.has(name)) {
            return this.loadingPromises.get(name);
        }

        const promise = Assets.load(url).then(texture => {
            this.resourceMap.set(name, texture);
            this.loadingPromises.delete(name);
            return texture;
        });

        this.loadingPromises.set(name, promise);
        return promise;
    }

    static get(name) {
        return this.resourceMap.get(name);
    }

    static has(name) {
        return this.resourceMap.has(name);
    }

    static remove(name) {
        this.resourceMap.delete(name);
        this.loadingPromises.delete(name);
    }

    static getAll() {
        return this.resourceMap;
    }

    static destroy() {
        this.resourceMap.clear();
        this.loadingPromises.clear();
    }
}

export default ResourceManager;